package com.jinliang.thinkinredis.controller;

import com.jinliang.thinkinredis.config.PowerReq;
import com.jinliang.thinkinredis.config.RedissionLock;
import org.redisson.api.RLock;
import org.redisson.api.RedissonClient;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Lazy;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.Map;
import java.util.concurrent.TimeUnit;

@RestController
@RequestMapping("/hello")
public class RedisHello {

    @Autowired
    private RedissonClient redissonClient;

    @Autowired
    private IRedissonService redissonService;

    Logger logger = LoggerFactory.getLogger(RedisHello.class);

    @RequestMapping("/ano")
    public Map<String, String> hello21(@RequestBody Map<String, String> param) {
        redissonService.tt(param.get("id"));
        return param;
    }

    @RedissionLock
    @PowerReq(lockIndexParam = 1)
    @RequestMapping("/lock")
    public Boolean hello1(@RequestBody Map<String, String> param) {
        redissonService.tt(param.get("id"));
        logger.info("业务已完成={}", param);
        return Boolean.TRUE;
    }

    @RequestMapping("/getlock")
    public Boolean hello221() {

        RLock disLock = redissonClient.getLock("123");
        Boolean isLock = null;
        try {
            //尝试获取分布式锁
            isLock = disLock.tryLock(5, 25, TimeUnit.SECONDS);
            if (isLock) {
                //TODO if get lock success, do something;
                Thread.sleep(15000);
            }
        } catch (Exception e) {
        } finally {
            // 无论如何, 最后都要解锁
            disLock.unlock();
        }

        return isLock;
    }
}
